<?php

/**
 * Created by lunzi.
 * User: lunzi
 * Date: 15-6-03
 * Time: 下午2:54
 */

class PC_Controller extends CI_Controller
{

    protected $admin = array(); //当前操作的商户
    protected $current_time = '';

    public function __construct()
    {
        parent::__construct();
        $this->current_time = time();
        $this->data['controller'] = $this->router->class;
        $this->data['method'] = $this->router->method;
        $this->data['admin_path'] = '/admin';
        $this->info = $this->session->userdata('HS_caipiao');
        $this->lang->load('message');
        $this->_init_visitor(); //初始化访问者
        $this->data['access'] = $this->Access();
        $this->parent_access();
        $this->authority = $this->Isauthority($this->data['controller']);
        if ($this->data['controller'] != "welcome") {
            $this->RBAC();
        }
        //$this->_init_view(); //初始视图
    }

    protected function _init_visitor()
    {
        $this->load->library('visitor');

        if (!$this->visitor->is_signed()) {
            if ($this->input->is_ajax_request()) {
                exit(getJsonOutput(array('status' => false, 'data' => '请先登录！')));
            } else {
                redirect('http://' . $_SERVER['HTTP_HOST'] . '/admin/login');
            }
        }
        $this->admin = $this->visitor->get_info('admin');
    }

    protected function _init_view()
    {
        $this->data['_global'] = array(
            'user' => $this->visitor->get_info(),
            'url' => array(
                'base' => base_url(),
                'api' => base_url() . 'api/',
                'static' => base_url() . 'static/',
                'pc'    =>  'cp.huishuojs.com',
                'qiniudn' => 'http://weipu.qiniudn.com/'
            ),
            'region_cache_time' => ''
        );
    }

    public function response($array = array(), $http_code = 200)
    {
        $CI = &get_instance();
        $callback = $CI->input->get('callback');

        header('HTTP/1.1: ' . $http_code);
        header('Status: ' . $http_code);

        if ($callback) {
            header('Content-type: application/javascript');
            exit($callback . '(' . json_encode($array) . ');');
        } else {
            header('Content-type: application/json');
            exit(json_encode($array));
        }
    }

    public function location_href($go_url)
    {
        echo "<script>window.location.replace('$go_url');</script>";
        exit;
    }

    //拼接地区
    public function get_post($data, $field)
    {
        $province = $data['province'];
        $city = $data['city'];
        $county = $data['county'];
        $province = explode(",", $province);
        $city = explode(",", $city);
        $county = explode(",", $county);
        $areas['area_no'] = $province[0] . ',' . $city[0] . ',' . $county[0];
        $areas['detail'] = $province[1] . $city[1] . $county[1];
        $data[$field] = serialize($areas);
        unset($data['province']);
        unset($data['city']);
        unset($data['county']);
        return $data;
    }

    //上传图片
    public function upload($files, $num = "jietu")
    {
        $info = $this->info;
        $upfile = $files[$num];
        //获取数组里面的值
        $name = $upfile["name"]; //上传文件的文件名
        $type = $upfile["type"]; //上传文件的类型
        $size = $upfile["size"]; //上传文件的大小
        $tmp_name = $upfile["tmp_name"]; //上传文件的临时存放路径
        //取扩展名
        $file_ext = explode(".", $name);
        $file_ext = $file_ext[count($file_ext) - 1];
        $file_ext = strtolower($file_ext);
        $newname = (time() - 2) . "_" . ($info['admin']['id']) . "." . $file_ext;
        if ($num != "jietu") { //防止2次上传图片名重复被覆盖
            $newname = (time() - 1) . "_" . ($info['admin']['id']) . "." . $file_ext;
        }
        $error = $upfile["error"];
        move_uploaded_file($tmp_name, 'public_source/upload/' . $newname);
        $destination = '/public_source/upload/' . $newname;
        return $destination;
    }

    //上传多图
    public function group_upload($files, $num = "desc_jietu")
    {
        $info = $this->info;
        $upfile = $files[$num];
        $destination = "";
        $name_array = $upfile["name"]; //上传文件的文件名
        //获取数组里面的值
        foreach ($name_array as $key => $value) {
            if ($value) {
                $name = $upfile["name"][$key]; //上传文件的文件名
                $type = $upfile["type"][$key]; //上传文件的类型
                $size = $upfile["size"][$key]; //上传文件的大小
                $tmp_name = $upfile["tmp_name"][$key]; //上传文件的临时存放路径
                //取扩展名
                $file_ext = explode(".", $name);
                $file_ext = $file_ext[count($file_ext) - 1];
                $file_ext = strtolower($file_ext);
                $newname = (time() + $key) . "_" . ($info['admin']['id']) . "." . $file_ext;
                $error =  $upfile["error"][$key];
                move_uploaded_file($tmp_name, 'public_source/upload/' . $newname);
                $destination .= '/public_source/upload/' . $newname . ";";
            }
        }
        if ($destination) {
            $destination = substr($destination, 0, -1);
        }
        return $destination;
    }

    //递归数组
    public function merge_node($node, $pid = 0)
    {
        $arr = array();
        foreach ($node as $k => $val) {
            if ($val['pid'] == $pid) {
                $val['child'] = $this->merge_node($node, $val['node_id']);
                $arr[] = $val;
            }
        }
        return $arr;
    }

    //获取父权限
    public function parent_access()
    {

        $admin_id = $this->admin['id'];
        $role_id = $this->admin['rid'];
        $this->load->model('access_model');
        $access = $this->access_model->getAccessAll($where = array('role_id' => $role_id));
        $this->load->model('node_model');
        foreach ($access as $key => $value) {
            $tmp = $this->node_model->checkNode(array('node_id' => $value['node_id'], 'pid' => 0));
            if ($tmp) {
                $nodes[] = $tmp['node_name'];
            }
        }
        $this->data['parent_access'] = $nodes; //管理员权限

        //所有父节点 权限
        $parent_nodes = $this->node_model->getNodeAll(array("pid" => 0));
        foreach ($parent_nodes as $k => $v) {
            $parent_nodes[$k] = $v['node_name'];
        }
        $this->data['all_node'] = $parent_nodes; //
    }

    //获取权限
    public function Access()
    {

        $admin_id = $this->admin['id'];
        $role_id = $this->admin['rid'];
        $this->load->model('access_model');
        if ($role_id == 1) {
            $access = $this->access_model->getAccessAll(); //超级管理员
        } else {
            $access = $this->access_model->getAccessAll($where = array('role_id' => $role_id));
        }
        foreach ($access as $key => $value) {
            $this->load->model('node_model');
            $nodes[] = $this->node_model->checkNode(array('node_id' => $value['node_id']));
        }
        $nodes = $this->merge_node($nodes);
        return $nodes;
    }

    //权限控制
    protected function RBAC()
    {
        $admin_id = $this->admin['id']; //username=admin  123456
        $role_id = $this->admin['rid'];
        //去数据中读取权限
        $this->load->model('access_model');
        $access = $this->access_model->getAccessAll($where = array('role_id' => $role_id));
        $controller = $this->data['controller']; //获取当前控制器名称
        $method = $this->data['method']; //获取当前方法名称 
        $this->load->model('node_model');
        $controller_nodes = $this->node_model->checkNode(array('node_name' => $controller, 'pid' => 0));
        $nodes = $this->node_model->checkNode(array('node_name' => $method, 'pid' => $controller_nodes['node_id']));
        if ($role_id != 1) {
            if ($controller_nodes && $nodes) {
                $is_auth = false;
                foreach ($access as $key => $value) {
                    if ($value['node_id'] == $nodes['node_id']) {
                        $is_auth = true;
                    }
                }
                if (!$is_auth) {
                    show_error("您没有权限", 404, "权限错误");
                    exit;
                }
            }
        }
    }

    //判断权限
    protected function Isallow($c, $m)
    {
        $admin_id = $this->admin['id']; //username=admin  123456
        $role_id = $this->admin['rid'];
        //去数据中读取权限
        $this->load->model('access_model');
        $access = $this->access_model->getAccessAll($where = array('role_id' => $role_id));
        $this->load->model('node_model');
        $controller_nodes = $this->node_model->checkNode(array('node_name' => $c, 'pid' => 0));
        $nodes = $this->node_model->checkNode(array('node_name' => $m, 'pid' => $controller_nodes['node_id']));
        //print_r($nodes);exit;
        if ($role_id != 1) {
            if ($controller_nodes && $nodes) {
                $is_auth = false;
                foreach ($access as $key => $value) {
                    if ($value['node_id'] == $nodes['node_id']) {
                        $is_auth = true;
                    }
                }
                return $is_auth;
            }
        } else {
            return true;
        }
    }

    public function Isauthority($c)
    {
        //判断权限
        $this_data['add_status'] = 1;
        $this_data['edit_status'] = 1;
        $this_data['delete_status'] = 1;
        $this_data['del_status'] = 1;
        if ($c == 'branch') {
            $this_data['open_status'] = 1;
            $this_data['openall_status'] = 1;
            if ($this->Isallow($c, 'open')) $this_data['open_status'] = 2;
            if ($this->Isallow($c, 'open_all')) $this_data['openall_status'] = 2;
        }
        if ($c == 'role') {
            $this_data['set_status'] = 1;
            if ($this->Isallow('access', 'edit_page')) $this_data['set_status'] = 2;
        }

        if ($c == 'opinion') {
            $this_data['details_status'] = 1;
            if ($this->Isallow($c, 'look_details')) $this_data['details_status'] = 2;
        }
        if ($this->Isallow($c, 'add_page')) $this_data['add_status'] = 2;
        if ($this->Isallow($c, 'edit_page')) $this_data['edit_status'] = 2;
        if ($this->Isallow($c, 'delete')) $this_data['del_status'] = 2;
        if ($this->Isallow($c, 'delete_all')) $this_data['delete_status'] = 2;
        return $this_data;
    }
    /**
     * 用户资金更换，后续操作 已废弃
     * @param type $user
     * @param type $parent_user
     */
    public function zhitui($user = array(), $parent_user = array())
    {
        $this->load->model('user_model');
        if ($user['parent_id'] > 0) {
            $where = array('id' => $user['parent_id']);
            $shouru = $user['price'] * 0.3;
            //$performance=$user['price']+$parent_user['performance'];
            $next_count = $parent_user['next_count'] + 1;
            $update = array('money' => $parent_user['money'] + $shouru, 'balance' => $parent_user['balance'] + $shouru, 'next_count' => $next_count);
            $result = $this->user_model->editUser($where, $update);
            if ($result) {
                $this->load->model('user_level_model');
                $level_info = $this->user_level_model->checkUserLevel(array('id' => $parent_user['user_level']));
                $data[] = array(
                    'user_id' => $parent_user['id'],
                    'username' => $parent_user['username'],
                    'true_name' => $parent_user['true_name'],
                    'money' => $shouru,
                    'type' => 'direct',
                    'remark' => '您的下级' . $user['true_name'] . '给你带来' . $shouru . '收入,',
                    'type_name' => '直推',
                    'user_level_name' => $level_info['user_level_name'],
                    'from_user_id' => $user['id'],
                    'from_user_name' => $user['username'],
                    'create_time' =>  time()
                );
                $this->add_money_log($data);
            } else {
                return false;
            }
        }
        return true;
    }
    /**
     * 
     * @return boolean直推奖2
     */
    public function zhitui2($user = array(), $parent_user = array())
    {
        $this->load->model('user_model');
        if ($user['parent_id'] > 0) {
            $this->load->model('user_level_model');
            $level_info = $this->user_level_model->checkUserLevel(array('id' => $parent_user['user_level']));
            $parent_user['user_level_name'] = $level_info['user_level_name'];
            $parent_user['use_level_id'] = $level_info['use_id'];
            $where = array('id' => $user['parent_id']);
            $lv = $level_info['zhitui'];
            /*switch ($parent_user['use_level_id']) {
                     case '1':
                         $lv=0.3;
                         break;
                     case '2':
                         $lv=0.38;
                         break;
                     case '3':
                         $lv=0.43;
                         break;
                     default:
                         break;
                 }*/
            $shouru = $user['price'] * $lv;
            //$performance=$user['price']+$parent_user['performance'];
            $next_count = $parent_user['next_count'] + 1;
            $update = array('money' => $parent_user['money'] + $shouru, 'balance' => $parent_user['balance'] + $shouru, 'next_count' => $next_count);
            $result = $this->user_model->editUser($where, $update);
            if ($result) {
                $data[] = array(
                    'user_id' => $parent_user['id'],
                    'username' => $parent_user['username'],
                    'true_name' => $parent_user['true_name'],
                    'money' => $shouru,
                    'type' => 'direct',
                    'remark' => '您的下级' . $user['true_name'] . '给你带来' . $shouru . '收入,',
                    'type_name' => '直推',
                    'user_level_name' => $parent_user['user_level_name'],
                    'from_user_id' => $user['id'],
                    'from_user_name' => $user['username'],
                    'create_time' =>  time()
                );
                $this->add_money_log($data);
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 三级收入（平级奖） 已废弃
     * @pqram type $user 当前审核的用户
     * @param type $parent_user 父级用户
     * @param type $parent_parent_user 父级父级用户
     * @return bool
     */
    public function distribution($user = array(), $parent_user = array(), $parent_parent_user = array())
    {
        if ($parent_parent_user && $parent_user['parent_id'] == $parent_parent_user['id']) {
            $next_next_count = $parent_parent_user['next_next_count'] + 1;
            // $performance=$parent_parent_user['performance']+$user['price']; //此处业绩在下面计算
            $update = array();
            $where = array();
            $where['id'] = $parent_parent_user['id'];
            //$update['performance']=$performance;
            $update['next_next_count'] = $next_next_count;
            $money_range = 0;
            $money = 0;
            $distribution = 'range';
            $distribution_desc = '极差';
            $this->load->model('user_level_model');
            $money_range = $this->user_level_model->level_rang($parent_parent_user['user_level'], $parent_user['user_level']);

            if ($parent_parent_user['user_level'] == $parent_user['user_level']) {
                $distribution = 'concur';
                $distribution_desc = '互助';
            }
            if ($money_range != 0) {
                $this->load->model('user_model');
                $money = $user['price'] * $money_range;
                $update['money'] = $parent_parent_user['money'] + $money;
                $update['balance'] = $parent_parent_user['balance'] + $money;
            }
            $result = $this->user_model->editUser($where, $update);
            if ($result && $money > 0) {
                $data[] = array(
                    'user_id' => $parent_parent_user['id'],
                    'username' => $parent_parent_user['username'],
                    'true_name' => $parent_parent_user['true_name'],
                    'money' => $money,
                    'type' => $distribution,
                    'remark' => '您的下级' . $user['true_name'] . '，给你带来' . $money . $distribution_desc . '收入,',
                    'create_time' =>  time()
                );
                $this->add_money_log($data);
            }
        }
        return true;
    }
    /**
     * 新增会员如果有父级处理
     */
    public function shouru($user, $parent_user, $parent_parent_user, $levels = 1, $is_ping = false, $end_level = 3, $is_start = true, $sfanzt = false)
    {


        $this->load->model('user_model');
        $this->load->model('user_level_model');
        if (!isset($user['use_level_id'])) {
            $user_level = $this->user_level_model->checkUserLevel(array('id' => $user['user_level']));
            $user['use_level_id'] = $user_level['use_id'];
            $user['user_level_name'] = $user_level['user_level_name'];
        }
        if (!isset($parent_user['use_level_id'])) {
            $user_level = $this->user_level_model->checkUserLevel(array('id' => $parent_user['user_level']));
            $parent_user['use_level_id'] = $user_level['use_id'];
            $parent_user['user_level_name'] = $user_level['user_level_name'];
        }
        if (!isset($parent_parent_user['use_level_id'])) {
            $user_level = $this->user_level_model->checkUserLevel(array('id' => $parent_parent_user['user_level']));
            $parent_parent_user['use_level_id'] = $user_level['use_id'];
            $parent_parent_user['user_level_name'] = $user_level['user_level_name'];
        }



        if ($parent_parent_user && $is_start) {
            //判断是否勾选按锁定值来分佣,最先判断的话 佣金会一直往下查找符合条件的。如果在levels 赋值后的话 会跳过当前级别佣金
            $isfenyong = false;
            if ($sfanzt) {
                if ($parent_parent_user['zhuangtai'] == '已解锁') {
                    $isfenyong = true;
                }
            } else {
                $isfenyong = true;
            }
            if (($parent_parent_user['use_level_id'] >= $parent_user['use_level_id']) && ($parent_parent_user['use_level_id'] >= $levels  && $isfenyong)) {

                $update = array();
                $where = array();
                $where['id'] = $parent_parent_user['id'];
                $money_range = 0;
                $money = 0;

                //                    if($parent_parent_user['user_level']==$end_level && $is_ping){
                //                        $distribution='concur';
                //                        $distribution_desc='互助';
                //                        $money_range=0.02;
                //						$is_ping=false;
                //                    }else
                if ($parent_parent_user['use_level_id'] == $levels && $is_ping) {
                    //暂时不需要互助
                    // $distribution = 'concur';
                    // $distribution_desc = '互助';
                    // $money_range = 0.02;
                    // $is_ping = false;



                } else if ($parent_parent_user['use_level_id'] > $levels) {
                    $distribution = 'range';
                    $distribution_desc = '极差';
                    $this->load->model('user_level_model');
                    //error_log('parent_parent_user:'.var_export($parent_parent_user,1)."\n",3,'D:\www\mammon\log.txt');
                    $money_range = $this->user_level_model->level_rang($parent_parent_user['use_level_id'], $levels);
                    //error_log('$money_range:'.var_export($money_range,1)."\n",3,'D:\www\mammon\log.txt');
                    $is_ping = false; //本次版本去掉平级奖
                }
                //判断获得佣金比率是否大于0
                $levels = $parent_parent_user['use_level_id']; //将当前上级等级重新赋值
                if ($money_range > 0 && $isfenyong) {
                    $this->load->model('user_model');
                    $money = $user['price'] * $money_range;
                    $update['money'] = $parent_parent_user['money'] + $money;
                    $update['balance'] = $parent_parent_user['balance'] + $money;
                    $result = $this->user_model->editUser($where, $update);
                    if ($result && $money > 0) {
                        $data[] = array(
                            'user_id' => $parent_parent_user['id'],
                            'username' => $parent_parent_user['username'],
                            'true_name' => $parent_parent_user['true_name'],
                            'money' => $money,
                            'type' => $distribution,
                            'type_name' => $distribution_desc,
                            'remark' => '您的下级' . $user['true_name'] . '，给你带来' . $money . $distribution_desc . '收入,',
                            'create_time' =>  time(),
                            'user_level_name' => $parent_parent_user['user_level_name'],
                            'from_user_id' => $user['id'],
                            'from_user_name' => $user['username'],
                        );
                        $this->add_money_log($data);
                    }
                }
            }

            if ($parent_parent_user['parent_id']) {

                $parent_parent_user2 = array();
                $parent_parent_user2 = $this->user_model->checkUser(array('user.id' => $parent_parent_user['parent_id']));


                $this->shouru($user, $parent_parent_user, $parent_parent_user2, $levels, $is_ping, $end_level, $is_start, $sfanzt);
            }
        }
        return true;
    }
    /**
     * 添加收入记录
     */
    public function add_money_log($data = array())
    {
        if ($data) {
            $this->load->model('money_log_model');
            foreach ($data as $key => $value) {
                $this->money_log_model->addMoneyLog($value);
            }
        }
        return true;
    }
    /**
     * 添加报单币日志log
     */
    public function add_system_money_log($data = array())
    {
        if ($data) {
            $this->load->model('system_money_rizhi_model');
            foreach ($data as $key => $value) {
                $this->system_money_rizhi_model->addSystemMoneyRizhi($value);
            }
        }
        return true;
    }
    /**
     * 会员等级更新,已废弃
     */
    public function update_level()
    {
        $this->load->model('user_model');
        $group_money = $this->user_model->select('sum(price) as group_performance')->find();
        $today = date("Y-m-d");
        $day = $this->getthemonth($today);
        $firstday =  strtotime($day[0]);
        $lastday = strtotime($day[1]);
        $mouth_money_tmp = $this->user_model->where("create_time between " . $firstday . " and " . $lastday)->select('sum(price) as mouth_money')->find();
        $mouth_money = $mouth_money_tmp['mouth_money'];

        $this->load->model('user_level_model');
        $user_level_where = array();
        $user_level_where['status'] = 1;
        $user_level_where['is_default !='] = '1';
        $user_level_where['group_performance <='] = $group_money['group_performance'];
        $user_levels = $this->user_level_model->getUserLevelList($user_level_where, '100', '0', 'group_performance asc');


        foreach ($user_levels as $key => $user_level_value) {
            if ($user_level_value['group_performance'] > $group_money) {
                break;
            } else {
                $user_tmp_where = array();
                $first_money = $user_level_value['other_performance'];
                $user_tmp_where['performance >='] = $first_money;
                if (isset($user_levels[$key + 1])) {
                    $last_money = $user_levels[$key + 1]['other_performance'];
                    $user_tmp_where['performance <'] = $last_money;
                }
                $user_tmp_where['user_level !='] = $user_level_value['id'];
                $user_tmp = array();
                $user_tmp =  $this->user_model->getUserList($user_tmp_where);


                foreach ($user_tmp as $user_key => $user_value) {
                    $parent_user_where = array();
                    $parent_user_where['parent_id'] = $user_value['id'];
                    $parent_user = $this->user_model->getUserList($parent_user_where, 1, 0, 'performance desc');


                    $parent_user_money = $user_value['performance'] - $parent_user[0]['performance'];

                    if ($parent_user_money > $first_money) {
                        $update_date = array();
                        $reward_money = $mouth_money * $user_level_value['reward'];
                        $update_date['money'] = $user_value['money'] + $reward_money;
                        $update_date['user_level'] = $user_level_value['id'];
                        $update_date['balance']   = $user_value['balance'] + $reward_money;


                        $return = $this->user_model->editUser(array('id' => $user_value['id']), $update_date);


                        if ($return) {
                            $add_money_log_data = array();
                            $add_money_log_data[] = array(
                                'user_id' => $user_value['id'],
                                'username' => $user_value['username'],
                                'true_name' => $user_value['true_name'],
                                'money' => $reward_money,
                                'type' => 'welfare',
                                'remark' => $user_value['true_name'] . '，恭喜您提升到' . $user_level_value['user_level_name'] . '奖励您' . $reward_money . '福利',
                                'create_time' =>  time()
                            );


                            $this->add_money_log($add_money_log_data);
                        }
                    }
                }
            }
        }
        return true;
    }
    /**
     * 更新会员级别，团队业绩
     */
    public function updatelevel($user, $mouth_money = '0')
    {

        if ($user['parent_id'] > 0) {
            $this->load->model('user_model');
            $parent_user_where = array('parent_id' => $user['parent_id']);
            //获取当前添加用户的父级下所有子级用户，即当前用户父级的直接下级

            $parent_user_child = $this->user_model->getUserList($parent_user_where, 2, 0, 'score desc');
            //获取父级用户信息
            $parent_user = $this->user_model->checkUser(array('user.id' => $user['parent_id']));
            //判断用户父级是否只有一个下级，如果有一个则肯定不满足升级条件，
            //升级条件是必须发展两条下线且团队业绩达到多少和减去最大团队业绩后剩余其他团队业绩总和达到多少
            //独立出去的高管也算
            $child_num = count($parent_user_child);
            if (!empty($parent_user['dulixiaji'])) {
                try {
                    $parent_user['dulixiaji'] = json_decode($parent_user['dulixiaji'], 1);
                    $child_num = $child_num + count($parent_user['dulixiaji']);
                    $sort_values = array_column($parent_user['dulixiaji'], 'yeji');
                    array_multisort($sort_values, SORT_DESC, $parent_user['dulixiaji']);
                } catch (Exception $e) {
                    $parent_user['dulixiaji'] = array();
                }
            } else {
                $parent_user['dulixiaji'];
            }
            if ($child_num > 1) {
                /*if(!$mouth_money){
                           $today = date("Y-m-d");
                           $day=$this->getthemonth($today);
                           $firstday=  strtotime($day[0]);
                           $lastday= strtotime($day[1]);
                           $mouth_money_tmp=$this->user_model->where("create_time between ".$firstday ." and ".$lastday )->select('sum(price) as mouth_money')->find();
                           $mouth_money=$mouth_money_tmp['mouth_money'];
                           
                        }*/
                if ($parent_user_child[0]['score'] > 0) {
                    //查找当前用户去掉最大业绩的下级后其他团队业绩之和
                    $other_performance_tmp =  $this->user_model->getFeildList(array('id !=' => $parent_user_child[0]['id'], 'parent_id' => $parent_user['id']), 'sum(score) as other_performance,sum(price) as other_price ');
                    //$other_price_tmp=  $this->user_model->getFeildList(array('id !='=>$parent_user_child[0]['id'],'parent_id'=>$parent_user['id']),'sum(price) as other_price ');
                    $other_performance = 0;
                    if (isset($other_performance_tmp[0]['other_performance'])) {
                        $other_performance = $other_performance_tmp[0]['other_performance'];
                        $other_price = $other_performance_tmp[0]['other_price'];
                        if ($other_price > 0) {
                            $other_performance = $other_performance + $other_price;
                        }
                    }
                    //计算的总业绩加上独立前的下级业绩
                    if (!empty($parent_user['dulixiaji']) && is_array($parent_user['dulixiaji'])) {
                        foreach ($parent_user['dulixiaji'] as $key => $value) {
                            //判读已经独立的下级高管中有没有比没有独立的下级业绩还高的，
                            //如果有则其他市场业绩就是总业绩减去独立出去的下级中业绩最高的一个下级
                            if ($value['yeji'] > $parent_user_child[0]['score']) {
                                $other_performance += $parent_user_child[0]['score'];
                            } else {
                                $other_performance += $value['yeji'];
                            }
                        }
                    }
                    $this->editUserLevels($parent_user, $other_performance, $mouth_money);
                } else {
                    $this->updatelevel2($parent_user, $mouth_money);
                }
            }
            if ($parent_user['parent_id']) {
                $this->updatelevel($parent_user, $mouth_money);
            }
        }
    }
    /**
     * 没有第三级下处理晋升
     */
    public function updatelevel2($parent_user, $mouth_money)
    {
        $this->load->model('user_model');
        $user_first_child = $this->user_model->getUserList(array('parent_id' => $parent_user['id']), '1', 0, 'price desc');
        $count_price = $this->user_model->getFeildList(array('parent_id' => $parent_user['id']), ' sum(price) as count_price');

        $other_performance = $count_price[0]['count_price'] - $user_first_child[0]['price'];
        $this->editUserLevels($parent_user, $other_performance, $mouth_money);
    }
    /**
     * 修改用户等级
     */
    private function editUserLevels($parent_user, $other_performance, $mouth_money)
    {
        $this->load->model('user_level_model');

        $user_level = array();
        $user_level_where = array();
        $user_level_where = array('status' => 1, 'group_performance <=' => $parent_user['score'], 'other_performance <=' => $other_performance);

        $user_level = $this->user_level_model->getUserLevelList($user_level_where, '1', 0, 'other_performance desc');
        $old_level = $this->user_level_model->checkUserLevel(array('id' => $parent_user['user_level']));
        //没有降级处理
        if ($user_level[0] && $user_level[0]['id'] != $parent_user['user_level'] && $user_level[0]['sort'] > $old_level['sort']) {
            $reward_money = $mouth_money * $user_level[0]['reward'];

            $update_date['money'] = $parent_user['money'] + $reward_money;
            $update_date['user_level'] = $user_level[0]['id'];
            $update_date['balance']   = $parent_user['balance'] + $reward_money;
            $update_date['shengji_time'] = time();
            $update_date['update_parent'] = $user_level[0]['id'] == 4 ? 1 : 0;

            $return = $this->user_model->editUser(array('id' => $parent_user['id']), $update_date);
            //记录升级日志
            $user_level_log = array();
            $user_level_log['from_level'] = $parent_user['user_level'];
            $user_level_log['to_level'] = $update_date['user_level'];
            $user_level_log['user_id'] = $parent_user['id'];
            $user_level_log['create_time'] = time();
            $this->load->model('user_level_log_model');
            $this->user_level_log_model->addUserLevelLog($user_level_log);

            if ($return && $reward_money > 0) {
                $add_money_log_data = array();
                $add_money_log_data[] = array(
                    'user_id' => $parent_user['id'],
                    'username' => $parent_user['username'],
                    'true_name' => $parent_user['true_name'],
                    'money' => $reward_money,
                    'type' => 'welfare',
                    'remark' => $parent_user['true_name'] . '，恭喜您提升到' . $user_level[0]['user_level_name'] . '奖励您' . $reward_money . '福利',
                    'create_time' =>  time()
                );


                $this->add_money_log($add_money_log_data);
                if ($parent_user['parent_id']) {
                    $this->updatelevel($parent_user, $mouth_money);
                }
            }
        }
    }

    /**
     * 添加会员后处理业绩
     */
    public function getperformance($user, $first = 1)
    {
        if (empty($user['source_user_id'])) {
            $user['source_user_id'] = $user['id'];
        }
        $this->load->model('user_yeji_log_model');

        if ($user['parent_id']) {
            $parent_user = $this->user_model->checkUser(array('user.id' => $user['parent_id']));
            if ($parent_user) {
                $this->load->model('user_model');
                $update = array();
                $update['performance'] = $parent_user['performance'] + $user['price'];
                $update['score'] = $parent_user['score'] + $user['price'];
                $this->user_model->editUser(array('id' => $parent_user['id']), $update);
                //保存用户业绩记录
                $this->user_yeji_log_model->save([
                    'user_id' => $parent_user['id'],
                    'source_user_id' => $user['source_user_id'],
                    'zhitui' => $first == 1 ? $user['price'] : 0,
                    'tuandui' => $user['price'],
                    'create_time' => time(),
                    'day' => date('Y-m-d'),
                ]);
                if ($parent_user['parent_id'] > 0) {
                    $parent_user['source_user_id'] = $user['source_user_id'];
                    $parent_user['price'] = $user['price'];
                    $this->getperformance($parent_user, 0);
                }
            }
        }
    }
    /**
     * 获取当前月份第一天和最后一天
     */
    function getthemonth($date)
    {
        $firstday = date('Y-m-01', strtotime($date));
        $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
        return array($firstday, $lastday);
    }
    /**
     * php异步请求
     * @param $host string 主机地址
     * @param $path string 路径
     * @param $param array 请求参数
     * @return string
     */
    public static function asyncRequest($url, $param = array(), $port = 80, $header = array())
    {
        $urlinfo = parse_url($url);
        //$host = $urlinfo['host'] = 'localhost';
        // $urlinfo['host'] = str_replace('10.2.7.108','127.0.0.1',$urlinfo['host']);
        $host = $urlinfo['host'];
        $path = $urlinfo['path'];
        $query = isset($param) ? http_build_query($param) : '';

        $errno = 0;
        $errstr = '';
        $timeout = 18000; //连接超时时间（S）

        $fp = @fsockopen($host, $port, $errno, $errstr, $timeout);
        //$fp = stream_socket_client("tcp://".$host.":".$port, $errno, $errstr, $timeout);

        if (!$fp) {

            return '连接失败';
        }
        if ($errno || !$fp) {

            return $errstr;
        }

        stream_set_blocking($fp, 0); //非阻塞
        stream_set_timeout($fp, 300); //响应超时时间（S）
        $out  = "POST " . $path . " HTTP/1.1\r\n";
        $out .= "host:" . $host . "\r\n";
        $out .= "content-length:" . ($query) . "\r\n";
        $out .= "content-type:application/x-www-form-urlencoded\r\n";
        $out .= "connection:close\r\n\r\n";
        $out .= $query;

        $result = @fputs($fp, $out);
        usleep(3000);

        @fclose($fp);
        return $result;
    }
}
